package com.hc.common.datasource;


import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.Map;

public class DynamicSaasDataSource extends AbstractRoutingDataSource {
    private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>();


    @Override
    protected Object determineCurrentLookupKey() {
        return getDataSource();
    }
    public DynamicSaasDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }
    public  boolean existDataSource(Object dataSourceName) {
        Map<Object, DataSource> resolvedDataSources =super.getResolvedDataSources();
        return resolvedDataSources.get(dataSourceName) != null;
    }

    public Map<Object, DataSource> getAllDatasource(){
        return super.getResolvedDataSources();
    }

    public static String getDataSource() {
        return CONTEXT_HOLDER.get();
    }

    public static void setDataSource(String dataSource) {
        CONTEXT_HOLDER.set(dataSource);
    }
    public static void clearDataSource() {
        CONTEXT_HOLDER.remove();
    }
}
